<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\PersonModel;
use app\admin\model\ShopModel;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\TransferShop;
use app\mini\model\SysModelMini;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use app\mini\model\SysModelMiniCustomer;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;
class CustomerPrestoreGoods extends ApiCommon
{
    protected $customerModel;
    protected $customerConfigModel;
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function initialize()
    {
        $action = [
            'permission' => ['house_list','setcustomerage','setzycustomer','dsmonth','setmonth'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        $this->customerConfigModel = new CustomerConfigModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }

    /**
     * 列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function list(CustomerModel $customerModel): Json
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];

        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function list_export(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['export']  = 1;
        $type = $this->param['type'] ?? 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }

        if ($type == 1 || $type == 2 ){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '姓名',
                'telephone'      => '联系电话',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'source_name'      => '来源',
                'effective_entry'      => '是否进店',
                'grade_name'      => '会员等级',
                'nurse_name'      => '护理师',
                'customer_service_name'      => '客服',
                'shop_name'      => '门店/门诊',
                'turn_status'      => '转店状态',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 3){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'source_name'      => '来源',
                'new_join_shop_time'      => '进店时间',
                'grade_name'      => '会员等级',
                'nurse_name'      => '负责人',
                'shop_name'      => '门店/门诊',
                'customer_service_name'      => '客服',
                'turn_status'      => '转店状态',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 4){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '顾客姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'new_join_shop_time'      => '进店时间',
                'nurse_name'      => '护理师',
                'shop_name'      => '门店/门诊',
                'grade_name'      => '会员等级',
                'class_name'      => '客户分类',
                ''      => '消费时间',
                ''      => '服务时间',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 5){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '顾客姓名',
                'telephone'      => '手机号姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'new_join_shop_time'      => '进店时间',
                'nurse_name'      => '护理师',
                'shop_name'      => '门店/门诊',
                'grade_name'      => '会员等级',
                'class_name'      => '客户分类',
                ''      => '消费时间',
                ''      => '服务时间',

                'last_kftime'      => '回访时间',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 6){
            $callName = [
                'cj_time'      => '成交时间',
                'customer_name'      => '顾客姓名',
                'telephone'      => '手机号',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'source_name'      => '来源',
                'grade_name'      => '会员等级',
                'market_name'      => '市场',
                'shop_name'      => '店面',
                'nurse_name'      => '护理师',
                'cj_money'      => '成交金额',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
            ];

        }

        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新单列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function newOrderlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id']    = $this->userInfo['id'];
        $this->param['shopIds']    = $shopIds;
        $this->param['isNewOrder']    = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 回访列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function clientVisitlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id']    = $this->userInfo['id'];
        $this->param['shopIds']    = $shopIds;

        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 流失列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function drainlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isDrain'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 预警列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function warninglist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isWarning'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 审核列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function auditList(Service $serviceModel): Json
    {
        // $data = [
        //     'list' => '审核列表'
        // ];
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->auditList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 提交审核
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function submitAudit(Service $serviceModel)
    {
        // $data = [
        //     'list' => '审核列表'
        // ];
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->submitAudit($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 商机详情
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function read(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_phone'] = $this->userInfo['mobile'];

        $data = $customerModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取客户门诊id
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function readCustomerId(CustomerModel $customerModel): Json
    {
        $request = $this->param;

        $telephone = Db::name('customer')->where('id',$request['id'])->value('telephone');

        $ids = Db::name('customer')->alias('c')
            ->join('shop s', 's.shop_id = c.shop_id', 'LEFT')
            ->where('c.telephone',$telephone)->column('c.id','s.shop_type');


        return resultArray(['data' => $ids]);
    }

    /**
     * 添加
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function create(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $customerModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function update(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $customerModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingCategory(SettingCategory $settingCategory): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingCategory->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingCategory->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingInfo(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->settingInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function settingList(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getAllDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function setting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 添加
     * @param  Setting $settingModel
     * @return Json
     */
    public function createSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  Setting $settingModel
     * @return Json
     */
    public function updateSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 删除
     * @param  Setting $settingModel
     * @return Json
     */
    public function deleteSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->deleteData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 状态
     * @param  Setting $settingModel
     * @return Json
     */
    public function statusSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->statusData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 转店列表
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList(TransferShop $transferShop): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 转店列表 导出
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList_export(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        $callName = [
            'out_shop_name' => '转出门店/门诊',
            'create_time' =>'转出时间',
            'customer_name' =>'客户名称',
            'operator_name' => '操作员工',
            'in_shop_name' => '转入门店/门诊',
            'reason' => '转店原因'
        ];
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 手机号验证
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function verifyPhone(TransferShop $transferShop): Json
    {

        $data = $transferShop->verifyPhone($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 添加转店
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShop(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['error' => $transferShop->getError(), 'data'=>[]]);
    }

    /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function serviceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_shop_id'] = $this->userInfo['shop_id'];

        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $serviceModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }

        // 导出
        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'create_time'   =>'开卡日期',

                'customer_name' =>'顾客姓名',

                'kk_user_name' =>'开卡人',

                'shop_name' =>'开卡部门',

                'name' =>'开卡名称',

                'kk_money'     =>'开卡金额',
                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'consume_store_transfer'=>'消耗店转',

                'num'   =>'开卡次数',

                'yy_num'    =>'剩余次数',

                'start_time'    =>'开始时间',

                'end_time'      =>'结束时间',

                'sy_num'    =>'消耗次数',
                'remark'  =>'备注'
            ];


            if($data['list']){


                $downUrl = exportExcelData('服务列表导出',$callName,$data['list'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }

        return resultArray(['data' => $data]);
    }

    /**

     * 核销列表

     * @param  Service $serviceModel

     * @return Json

     */
    public function serveContent(Service $serviceModel): Json
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();

        $this->param['shopIds'] = $shopIds;

        $this->param['user_id'] = $this->userInfo['id'];

        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $serviceModel->getDataLog($this->param);

        if (!$data) {

            return resultArray(['error' => $serviceModel->getError().'23232']);

        }
        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            if(date('Y-m',strtotime($this->param['start_time'])) != date('Y-m',strtotime($this->param['endTime'])))
                return resultArray(['error' => "只能导出一个月内的数据"]);

            $callName = [

                'create_time'   =>'服务日期',

                'kk_time' =>'开卡日期',

                'customer_name' =>'客户姓名',

                'sex' =>'性别',

                'age' =>'年龄',

                'shop_name' =>'门店',

                'market_name'     =>'市场',

                'nurse_name'   =>'负责人',

                'name'    =>'卡项名称',

                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'consume_store_transfer'=>'消耗店转',

                'nurse_id_one_name'    =>'护理师1',

                'nurse_id_two_name'      =>'护理师2',

                'experience'    =>'服务类型',

                'fw_num'    =>'服务次数',

                'station_name'    =>'核销店长',

                'pt'    =>'核销平台',

                'mark'  =>'备注'

            ];


            if($data['service_log']){
                $downUrl = exportExcelData('核销列表导出',$callName,$data['service_log'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }
        return resultArray(['data' => $data]);


    }

    /**

     * 护理统计

     * @param  Service $serviceModel

     * @return Json

     */
    public function serviceNursing(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();

        $this->param['shopIds'] = $shopIds;

        $this->param['user_id'] = $this->userInfo['id'];

        $data = $serviceModel->getDataNursing($this->param);
//        $totalData = $serviceModel->getTotalData($this->param);
        // echo "<pre>";
        // print_r($data['service_log']);
        // exit;
        //print_r($data);
        if (!$data) {

            return resultArray(['error' => $serviceModel->getError()]);

        }
//        array_push($data['service_log'],$totalData);

        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'market_name'   =>'市场',

                'shop_name' =>'门店',

                'name' =>'员工姓名',

                'station_name' =>'等级',

                'bahennum' =>'疤痘护理',

                'mianbunum'     =>'面部护理',

                'shentinum'   =>'项目身体护理',

                'shengming'    =>'生命之源',

                'jingluotong'    =>'经络通',

                'shuganliqi'      =>'疏肝理气',

                'jichubushui'    =>'基础补水',

                'total'    =>'护理总数',

            ];


            if($data['service_log']){


                $downUrl = exportExcelData('护理统计明细',$callName,$data['service_log'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }


        return resultArray(['data' => $data]);


    }

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function readService(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,$serviceModel->getError()]);
    }

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function addServiceLog(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->addServiceLog($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


    /**
     * 调整服务卡项
     * @param  Service $serviceModel
     * @return Json
     */
    public function changeService(Service $serviceModel)
    {
        $this->param['user_id'] = $this->userInfo['id'];
        // echo "<pre>";
        // print_r($this->param);
        $data = $serviceModel->changeService($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


    /**
     * 余额变动记录
     * @param  BalanceLog $balanceLog
     * @return Json
     */
    public function createBalanceLog(BalanceLog $balanceLog): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $balanceLog->addData($this->param);
        if (!$data) {

            return resultArray(['error' => $balanceLog->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 每年重新搞一下名字
     */
    public function setCustomerAge(CustomerModel $customerModel):Json
    {
        $data = $customerModel->setCustomerAge($this->param);
        if (!$data) {

            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => []]);
    }

    /**
     * 更新进店时间
     * 更新转店状态
     */
    public function setCustomerStatus(CustomerModel $customerModel):Json
    {
        $param  = $this->param;
        $data = $customerModel->setCustomerStatus($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => '更新成功','data' => []]);
    }

    /**
     * 会员等级列表
     */
    public function getGradeList(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param  = $this->param;
        $data   = $CustomerGradeModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级的基础数据获取
     */
    public function addGradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级
     */
    public function addGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '添加成功','data' => $data]);
    }

    /**
     * 编辑会员等级
     */
    public function saveGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->saveGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '编辑成功','data' => $data]);
    }

    /**
     * 获取详情
     */
    public function gradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->gradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 某个客户的优惠券
     */
    public function getCouponProvide(): Json
    {
        $param      = $this->param;
        $shop_id    = $param['shop_id'] ?? 0;
        $customer_id= $param['customer_id'] ?? 0;
        $type= $param['type'] ?? 0;

        if ($shop_id == 0 && $customer_id == 0 ) {
            return resultArray(['error' => '数据类型错误']);
        }

        $where = array();
        if ($shop_id) {

        } else {
            array_push($where,['customer_id','=',$customer_id]);

            $c_where = [];

            array_push($c_where,['start_time','<',time()]);
            array_push($c_where,['end_time','>',time()]);
            $shop_goods = Db::name('coupon')->where($c_where)->column('id');

            array_push($where,['coupon_id','in',$shop_goods]);
        }
        $list       = Db::name('coupon_provide_customer')->where($where)->select()->toArray();
        $yhjIds     = array_column($list,'coupon_id');
        if ($yhjIds) {
            $files = [
                'id',
                'name',
                'use_type',
                'type',
                'use_threshold',
                'denomination',
                'start_time',
                'end_time',
                'status',
            ];
            $where = [];
            array_push($where,['id','in',$yhjIds]);
            if($type == 1){
                array_push($where,['type','=',$type]);
            }else if($type == 2){
                array_push($where,['type','=',$type]);
            }else if($type == 3){
                array_push($where,['type','=',$type]);
            }
            $yhjlist   = Db::name('coupon')->where($where)->column($files,'id');
            // print_r($yhjlist);exit;
        }
        foreach ($list as $key => $val){
            if ($yhjlist[$val['coupon_id']]['end_time'] >= time() && $yhjlist[$val['coupon_id']]['start_time'] <= time() && $yhjlist[$val['coupon_id']]['status'] != 1 ) {
                $list[$key]['status']    = 2;
            }
            if ($yhjlist[$val['coupon_id']]['start_time'] > time()) {
                $list[$key]['status']    = 3;
            }
            // print_r($val);
            // print_r($yhjlist);
            // $list[$key]['id']            = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['name']          = $yhjlist[$val['coupon_id']]['name'] ? $yhjlist[$val['coupon_id']]['name'] : '';
            $list[$key]['use_type']      = $yhjlist[$val['coupon_id']]['use_type'] ? $yhjlist[$val['coupon_id']]['use_type'] : 0;
            $list[$key]['use_threshold'] = $yhjlist[$val['coupon_id']]['use_threshold'] ? $yhjlist[$val['coupon_id']]['use_threshold'] : 0;
            $list[$key]['denomination']  = $yhjlist[$val['coupon_id']]['denomination'] ? $yhjlist[$val['coupon_id']]['denomination'] : 0;
            $list[$key]['start_time']    = $yhjlist[$val['coupon_id']]['start_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['start_time']) : 0;
            $list[$key]['end_time']      = $yhjlist[$val['coupon_id']]['end_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['end_time']) : 0;
            // $list[$key]['status']        = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['create_time']      = $list[$key]['create_time'] ? date('Y-m-d H:i:s',$list[$key]['create_time']) : 0;
            $list[$key]['use_time']      = $list[$key]['use_time'] ? date('Y-m-d H:i:s',$list[$key]['use_time']) : '未使用';
            $list[$key]['endTimeT']      = $yhjlist[$val['coupon_id']]['end_time'] ? $yhjlist[$val['coupon_id']]['end_time'] : 0;
            $type = $yhjlist[$val['coupon_id']]['type'] ?? 0;
            if ($type == 1) {
                // code...
                $type_name = '满减券';
            }else if($type == 2){
                $type_name = '满赠券';
            }else {
                $type_name = '兑换券';
            }
            $list[$key]['type_name']      = $type_name;
            $list[$key]['type']      = $type;
        }

        /* $i = 0;
        foreach ($list as $k => $v){

            if($v['endTimeT'] >= time()){

                $list_t[$i]['id'] =$v['id'];
                $list_t[$i]['coupon_id'] =$v['coupon_id'];
                $list_t[$i]['customer_id'] =$v['customer_id'];
                $list_t[$i]['staus'] =$v['staus'];
                $list_t[$i]['create_time'] =$v['create_time'];
                $list_t[$i]['use_time'] =$v['use_time'];
                $list_t[$i]['order_id'] =$v['order_id'];
                $list_t[$i]['order_sn'] =$v['order_sn'];
                $list_t[$i]['user_id'] =$v['user_id'];
                $list_t[$i]['name'] =$v['name'];
                $list_t[$i]['use_type'] =$v['use_type'];
                $list_t[$i]['use_threshold'] =$v['use_threshold'];
                $list_t[$i]['denomination'] =$v['denomination'];
                $list_t[$i]['start_time'] =$v['start_time'];
                $list_t[$i]['end_time'] =$v['end_time'];
                $list_t[$i]['type_name'] =$v['type_name'];
                $list_t[$i]['type'] =$v['type'];

                $i ++;
            }else{
                $list_t[0]['dd']=1;
            }

        } */
        /* echo '<pre>';
        print_r($list_t);exit; */
        return resultArray(['error' => '','data' => $list]);
    }
    /**
     * 某个客户的优惠券兑换时的客户信息
     */
    public function getCouponProvideCustomer(): Json
    {
        $param      = $this->param;
        $yhj_id     = $param['yhj_id'] ?? 0;

        $where = [];
        array_push($where,['id','=',$yhj_id]);
        $fubiaoInfo     = Db::name('coupon_provide_customer')->where($where)->find();
        if (empty($fubiaoInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $yhjInfo        = Db::name('coupon')->where('id','=',$fubiaoInfo['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $customerInfo   = Db::name('customer')->where('id','=',$fubiaoInfo['customer_id'])->find();
        if (empty($customerInfo)) {
            return resultArray(['error' => '客户不存在']);
        }
        $shopInfo   = Db::name('shop')->where('shop_id','=',$customerInfo['shop_id'])->find();
        if (empty($shopInfo)) {
            return resultArray(['error' => '店铺不存在']);
        }
        $personInfo   = Db::name('shop_person')->where('id','=',$customerInfo['nurse_id'])->find();
        if (empty($personInfo)) {
            return resultArray(['error' => '护理师不存在']);
        }
        $data = [];
        // 销售部门
        $data['sales_name']       = $shopInfo['shop_name']; //店名
        // 客户姓名
        $data['customer_name']    = $customerInfo['customer_name']; // 客户名称
        // 护理师（开单人）
        $data['sale_name']        = $personInfo['name']; // 护理师
        // 业务类型
        $data['business_type']    = $yhjInfo['use_type'] == 1 ? '疤痕' :'项目'; // 优惠券的类型
        // 订单类型
        $data['order_type']       = '补单'; // 默认补单
        // 销售组织
        $data['sales_organization']       = $shopInfo['market_name']; // 门店的归属市场
        // 发货组织
        $data['settlement_name']  = $shopInfo['market_name']; // 门店的归属市场
        // 发货部门
        $data['settlement_bumen_name']    = $shopInfo['market_name']; // 门店的归属市场
        // 发货仓库
        $data['settlement_cangku_name']  = $shopInfo['store_name'];  // 门店的归属市场
        // 成交日期
        $data['deal_time']        = date('Y-m-d'); // 当前时间
        $data['goodsList']        = []; // 可兑换的商品集合

        $goodsIds    = $yhjInfo['goods_id'];
        if ($goodsIds) {
            // code...
            $goodsList  = Db::name('shop_goods')->where('id','in',$goodsIds)->select()->toArray();
            foreach ($goodsList as $key => $val){
                $goodsList[$key]['pay_price'] = '0.00';
                $goodsList[$key]['number'] = '1';
            }
            $data['goodsList'] = $goodsList;
        }
        return resultArray(['error' => '获取成功','data' => $data]);
    }
    /**
     * 获取订单支付金额
     */
    public function getPayment(): Json
    {
        $param = $this->param;

        // 设置返回数据
        $balanceType = [
            1=>[
                'this' => 'zc_goods',
                'all'  => 'zc_allgoods'
            ],
            2=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
            3=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
            4=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
        ];
        $retuenData = [
            'zc_goods_y'    => '0.00', // 疤痕需要支付的余额
            'zc_goods_z'    => '0.00', // 疤痕需要支付的赠金
            'zc_goods_d'    => '0.00', // 疤痕需要支付的店转
            'zc_allgoods_z' => '0.00', // 疤痕需要支付的总金额
            'zc_fuwu_y'     => '0.00', // 服务需要支付的余额
            'zc_fuwu_z'     => '0.00', // 服务需要支付的赠金
            'zc_fuwu_d'     => '0.00', // 服务需要支付的店转
            'zc_allfuwu_z'  => '0.00',
            'yhj_list'      => [],
        ];

        //获取订单总金额
        $order_amout       = isset($param['order_amout']) ? $param['order_amout'] : 0;         // 订单总计
        $customer_id       = isset($param['customer_id']) ? intval($param['customer_id']) : 0; // 客户id
        $yhj_amount        = isset($param['yhj_amount']) ? abs($param['yhj_amount']) : 0;      // 优惠劵金额
        $order_type        = isset($param['order_type']) ? abs($param['order_type']) : 0;// 订单的业务类型
        $business_type     = isset($param['business_type']) ? abs($param['business_type']) : 0;// 订单的业务类型
        if($business_type == 0){
            $business_type = $order_type;
        }
        if (!in_array($business_type,[1,2,3,4]) || $customer_id == 0){
            return resultArray(['error' => '订单类型或客户数据错误']);
        }
        if ($order_amout < 0) {
            // 如果订单金额为0，则直接返回数据
            return resultArray(['error'=>'订单金额异常，无法获取客户支付金额']);
        }
        if ($order_amout == 0) {
            // 如果订单金额为0，则直接返回数据
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }

        // 按照当前逻辑，订单仅是服务或者疤痕，所以下述处理按照一种客户的余额进行处理

        $balanceList = Db::name('customer_balance')
            ->where([['customer_id','=',$customer_id]])
            ->field('money,complimentary_money,shop_transfer_money')->select()->toArray();
        $money = $complimentary_money = $shop_transfer_money = 0;
        foreach($balanceList as $k=>$v){
            $money = bcadd($money,$v['money'],2);
            $complimentary_money = bcadd($complimentary_money,$v['complimentary_money'],2);
            $shop_transfer_money = bcadd($shop_transfer_money,$v['shop_transfer_money'],2);
        }
        $customerMoney = bcadd(bcadd($money,$complimentary_money,2),$shop_transfer_money,2);
        $customerModel = new CustomerModel();
        $customerBalance =  $customerModel->getCustomerBalance($customer_id,$business_type); //获取客户的余额
        if($customerMoney<0){
            return resultArray(['error'=>'客户金额异常,无法下单']);
        }
        // 获取实际支付的订单金额数据和对应客户需要支付的金额数据
        $actual_order_amout  = bcsub($order_amout,$yhj_amount,2); // 获取订单的实际需要支付金额

        if ($actual_order_amout <= 0) {
            // code...
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }
        //
        // 本 增
        // 1 2
        // 1 1=0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 2 1=0 2>0 -此种情况先判断赠金是否够用，若够用则结束，若不够需要将本金扣为负数
        // 3 1=0 2<0 --
        // 4 1>0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 5 1>0 2>0 -此种情况按照本金/赠金的比例扣除本金和赠金，赠金最多全部抵扣，不可扣为负数，依旧不足时可将本金扣为负数
        // 6 1>0 2<0 --
        // 7 1<0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 8 1<0 2>0 -此种情况先判断赠金是否够用，若够用则结束，若不够需要将本金扣为负数
        // 9 1<0 2<0 --
        //
//         if ($complimentary_money == 0) { // 1,4,7 仅扣本
//            $retuenData[$balanceType[$business_type]['this'].'_y'] = $actual_order_amout;
//         } else if ($money <= 0 && $complimentary_money > 0) { // 2,7 新赠后本
//            if ($complimentary_money >= $actual_order_amout) {
//                $retuenData[$balanceType[$business_type]['this'].'_z'] = $actual_order_amout;
//            } else {
//                $retuenData[$balanceType[$business_type]['this'].'_z'] = $complimentary_money;
//                $retuenData[$balanceType[$business_type]['this'].'_y'] = bcsub($actual_order_amout,$complimentary_money,2);
//            }
//         } else if ($money > 0 && $complimentary_money > 0) { // 5 先比例在余额
//            // $bili       = bcdiv($complimentary_money,bcadd($money,$complimentary_money),10); // 获取折扣比例
//            // $bili_complimentary_money = bcmul($actual_order_amout,$bili,2); // 获取比例赠金，实际支付本金为避免误差用减法计算(实际支付-实际支付赠金)
//            $bilizengAdd = bcadd($money,$complimentary_money,2);
//            $bilizengCheng = bcmul($actual_order_amout,$complimentary_money,4); //
//            $bili_complimentary_money = bcdiv($bilizengCheng,$bilizengAdd,2);
//            if ($complimentary_money >= $bili_complimentary_money) { // 如果剩余赠金>=比例赠金
//                $pay_complimentary_money = $bili_complimentary_money; // 实际支付赠金为比例赠金
//            } else {
//                $pay_complimentary_money = $complimentary_money; // 实际支付赠金为剩余赠金
//            }
//            $retuenData[$balanceType[$business_type]['this'].'_z'] = $pay_complimentary_money;
//            $retuenData[$balanceType[$business_type]['this'].'_y'] = bcsub($actual_order_amout,$pay_complimentary_money,2);
//         }else{
//             return resultArray(['error'=>'客户金额异常']);
//         }
        $customerBalance['actual_order_amout'] = $actual_order_amout;
        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转

        $retuenData[$balanceType[$business_type]['this'].'_y'] = $pay_money['pay_benjin_amount'];
        $retuenData[$balanceType[$business_type]['this'].'_d'] = $pay_money['pay_dianzhuan_amount'];
        $retuenData[$balanceType[$business_type]['this'].'_z'] = $pay_money['pay_zengjin_amount'];

        // 设置支付总金额
        $retuenData[$balanceType[$business_type]['all'].'_z']  = $actual_order_amout;

        $yhjlist     = Db::name('coupon_provide_customer')->where([['customer_id','=',$customer_id],['staus','=',0]])->select()->toArray();

        $yhjzbIds    = array_unique(array_column($yhjlist,'coupon_id'));
        //$yhjZbList   = Db::name('coupon')->where([['use_type','=',$business_type],['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');
        $yhjZbList   = Db::name('coupon')->where([['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');

        $allList = [];
        foreach ($yhjlist as $key => $val){
            if (isset($yhjZbList[$val['coupon_id']])) {
                //时间满足
                if ($yhjZbList[$val['coupon_id']]['start_time'] <= time() && time() <= $yhjZbList[$val['coupon_id']]['end_time']) {

                    //金额满足
                    if ($yhjZbList[$val['coupon_id']]['use_threshold'] == 0 || $order_amout >= $yhjZbList[$val['coupon_id']]['use_threshold']){
                        $yhjlist[$key]['use_type']      = $yhjZbList[$val['coupon_id']]['use_type'];
                        $yhjlist[$key]['type']          = $yhjZbList[$val['coupon_id']]['type'];
                        $yhjlist[$key]['denomination']  = $yhjZbList[$val['coupon_id']]['denomination'];
                        $yhjlist[$key]['name']          = $yhjZbList[$val['coupon_id']]['name'];
                        $yhjlist[$key]['start_time']    = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['start_time']);
                        $yhjlist[$key]['end_time']      = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['end_time']);
                        array_push($allList,$yhjlist[$key]);
                    }
                }
            }
        }

        $retuenData['yhj_list']  = $allList;
        //  print_r($balanceList);exit;
        return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        //----

        //获取用户的余额
        $customerBalance = Db::name('customer_balance')->where([['customer_id','=',$customer_id]])->select()->toArray();
        $cusetomer_goods_order_amout = [];
        $cusetomer_fuwu_order_amout  = [];
        foreach ($customerBalance as $key => $val){
            if ($val['balance_category_id'] == 1){
                $cusetomer_order_amout['money']                 = $val['money'];
                $cusetomer_order_amout['complimentary_money']   = $val['complimentary_money'];
                $cusetomer_order_amout['shop_transfer_money']   = $val['shop_transfer_money'];
                $cusetomer_order_amout['bili']                  = empty($val) ?[] :explode('/', $val['proportion']) ;
            }else if($val['balance_category_id'] == 2){
                $cusetomer_fuwu_order_amout['money']                 = $val['money'];
                $cusetomer_fuwu_order_amout['complimentary_money']   = $val['complimentary_money'];
                $cusetomer_fuwu_order_amout['shop_transfer_money']    = $val['shop_transfer_money'];
                $cusetomer_fuwu_order_amout['bili']                  = empty($val) ?[] :explode('/', $val['proportion']) ;
            }
        }
        $is_order = 1;
        $is_goods = 1;
        $goods_order_amout = bcsub($goods_order_amout,$yhj_amount,2);
        if ($goods_order_amout > 0) {
            if (empty($cusetomer_order_amout)) {
                $is_order = 0;
            }else if ($cusetomer_order_amout['money'] == 0) {
                $is_order = 0;
            }else if ($cusetomer_order_amout['money'] > 0){
                if (empty($cusetomer_order_amout['bili']) || (isset($cusetomer_order_amout['bili'][0]) && empty($cusetomer_order_amout['bili'][0]))){
                    $blall  = 1;//总
                    $bly    = 1;//原
                    $blz    = 0;
                }else{
                    $blall  = $cusetomer_order_amout['bili'][0] + $cusetomer_order_amout['bili'][1];//总
                    $bly    = $cusetomer_order_amout['bili'][0];//原
                    $blz    = $cusetomer_order_amout['bili'][1];//曾
                }
                $zc_goods_y   = bcmul(bcdiv($bly,$blall,2),$goods_order_amout,2);//zc支付原
                $zc_goods_z   = bcsub($goods_order_amout,$zc_goods_y,2);//支付曾

                if ($zc_goods_y > $cusetomer_order_amout['money']) {
                    $is_order = 0;
                } else {
                    if ($zc_goods_z > $cusetomer_order_amout['complimentary_money']) {
                        $zc_z_chae      = bcsub($zc_goods_y,$cusetomer_order_amout['complimentary_money'],2);
                        $zc_y_jiachae   = bcadd($cusetomer_order_amout['money'],$zc_z_chae,2);
                        if ($zc_y_jiachae >= $cusetomer_order_amout['money']) {
                            $is_order = 0;
                        }else{
                            $zc_goods_y = $zc_y_jiachae;
                            $zc_goods_z = $zc_z_chae;
                        }
                    }
                    // print_r($is_order);exit;
                }
            }
        }else{
            $goods_order_amout = '0';
        }
        $fuwu_order_amout = bcsub($fuwu_order_amout,$yhj_amount,2);
        if ($fuwu_order_amout > 0) {
            if (empty($cusetomer_fuwu_order_amout) || !isset($cusetomer_fuwu_order_amout['money'])) {
                $is_goods = 0;
            }else if ($cusetomer_fuwu_order_amout['money'] == 0) {
                $is_goods = 0;
            }else if ($cusetomer_fuwu_order_amout['money'] > 0){
                if (empty($cusetomer_order_amout['bili']) || (isset($cusetomer_order_amout['bili'][0]) && empty($cusetomer_order_amout['bili'][0]))){
                    $blall  = 1;//总
                    $bly    = 1;//原
                    $blz    = 0;
                }else{
                    $blall  = $cusetomer_fuwu_order_amout['bili'][0] + $cusetomer_fuwu_order_amout['bili'][1];//总
                    $bly    = $cusetomer_fuwu_order_amout['bili'][0];//原
                    $blz    = $cusetomer_fuwu_order_amout['bili'][1];//曾
                }
                $zc_fuwu_y   = bcmul(bcdiv($bly,$blall,2),$fuwu_order_amout,2);//zc支付原
                $zc_fuwu_z   = bcsub($fuwu_order_amout,$zc_fuwu_y,2);//支付曾
                if ($zc_fuwu_y > $cusetomer_fuwu_order_amout['money']) {
                    $is_goods = 0;
                } else {
                    if ($zc_fuwu_z >= $cusetomer_fuwu_order_amout['complimentary_money']) {
                        $zc_z_chae      = bcsub($zc_fuwu_z,$cusetomer_fuwu_order_amout['complimentary_money'],2);
                        $zc_y_jiachae   = bcadd($cusetomer_fuwu_order_amout['money'],$zc_z_chae,2);
                        if ($zc_y_jiachae > $cusetomer_fuwu_order_amout['money']) {
                            $is_goods = 0;
                        }else{
                            $zc_fuwu_y = $zc_y_jiachae;
                            $zc_fuwu_z = $zc_z_chae;
                        }
                    }
                }
            }
        }else{
            $fuwu_order_amout = '0';
        }
        if ($is_order == 0 || $is_goods ==0) {
            return resultArray(['error' => '客户余额不足']);
        }
        $data                  = [];
        $data['zc_goods_y']    = $zc_goods_y ?? "0";
        $data['zc_goods_z']    = $zc_goods_z ?? "0";
        $data['zc_allgoods_z'] = $goods_order_amout.'';
        $data['zc_fuwu_y']     = $zc_fuwu_y ?? "0";
        $data['zc_fuwu_z']     = $zc_fuwu_z ?? "0";
        $data['zc_allfuwu_z']  = $fuwu_order_amout.'';

        $yhj_type    = $goods_order_amout > 0 ? 1 : 2 ;
        $order_amout = $goods_order_amout>0 ? $goods_order_amout : $fuwu_order_amout;

        $yhjlist     = Db::name('coupon_provide_customer')->where([['customer_id','=',$customer_id],['staus','=',0]])->select()->toArray();

        $yhjzbIds    = array_unique(array_column($yhjlist,'coupon_id'));
        $yhjZbList   = Db::name('coupon')->where([['use_type','=',$yhj_type],['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');

        $allList = [];
        // print_r($yhjZbList);exit();
        foreach ($yhjlist as $key => $val){
            if (isset($yhjZbList[$val['coupon_id']])) {
                //时间满足
                if ($yhjZbList[$val['coupon_id']]['start_time'] <= time() && time() <= $yhjZbList[$val['coupon_id']]['end_time']) {

                    // print_r($yhjZbList[$val['coupon_id']]['use_threshold']);
                    // print_r('---'.$key);
                    // print_r('---'.$order_amout);
                    //金额满足
                    if ($yhjZbList[$val['coupon_id']]['use_threshold'] == 0 || $order_amout >= $yhjZbList[$val['coupon_id']]['use_threshold']){
                        $yhjlist[$key]['use_type']      = $yhjZbList[$val['coupon_id']]['use_type'];
                        $yhjlist[$key]['type']          = $yhjZbList[$val['coupon_id']]['type'];
                        $yhjlist[$key]['denomination']  = $yhjZbList[$val['coupon_id']]['denomination'];
                        $yhjlist[$key]['name']          = $yhjZbList[$val['coupon_id']]['name'];
                        $yhjlist[$key]['start_time']    = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['start_time']);
                        $yhjlist[$key]['end_time']      = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['end_time']);
                        array_push($allList,$yhjlist[$key]);
                    }
                }
            }
        }

        $data['yhj_list']  = $allList;
        return resultArray(['data' => $data]);
    }
    /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 服务列表导出
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList_export(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export'] = 1;
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        $callName = ['create_time' => '服务日期','customer_name' =>'客户姓名','sex_name' =>'性别','age' => '年龄','shop_name' => '门店','market_name' => '市场','shop_name' => '服务人员','service_type_name' => '服务类型','sy_num' => '服务次数'];
        // print_r($callName);exit;
        $downUrl = exportExcelData('service',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList(ReturnVist $ReturnVist): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList_export(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        $callName = [
            'customer_name' => '客户名称',
            'telephone' =>'门店名称',
            'return_visitor_name' =>'员工名称',
            'return_visit_time' => '客访时间',
            'return_visit_content' => '客访内容',
            'create_time' => '创建时间'
        ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function addVistList(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'创建成功']);
    }


    /**
     * 获取修复进展
     */
    public function repairPlanList(ReturnVist $ReturnVist): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->getRepairPlanList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 新增修复方案
     */
    public function addPlanList(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->addRepairData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'创建成功']);
    }

    /**
     * 回访列表
     */
    public function returnReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }
    /**
     * 回访列表
     */
    public function returnReturnVistT_export(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['list_type'] = 1;
        $this->param['export']  = 1;
        $data = $ReturnVistT->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }

        $callName = [
            'return_visit_time' => '回访时间',
            'customer_name' =>'顾客姓名',
            'market_name' =>'归属市场',
            'shop_name' => '归属门店',
            'nurse_name' => '责任护理师',
            'result' => '回访结果',
            'result_name' => '问题分类',
            'total' => '综合评分',
            'early_warning' => '是否预警',
            'accountability' => '是否追责',
        ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }
    /**new
     * 创建回访
     */
    public function addReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => [],'error' => '添加成功']);
    }

    /**
     * 更新回访
     */
    public function saveReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data,'error' => '添加成功']);
    }

    /***
     *添加跟进
     */
    public function addReturnVistTLog(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->addReturnVistTLog($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data,'error' => '添加成功']);
    }

    /***
     *获取回访详情
     */
    public function readReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->readReturnVistT($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /***
     * 获取优惠券的核销记录
     */
    public function getWriteOff(): json
    {
        $request = $this->param;
        // 获取需要的搜索参数 //
        $page  = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 15;
        $customer_name = $request['customer_name'] ?? 0;
        $shop_name     = $request['shop_name'] ?? 0;
        $market_id     = $request['market_id'] ?? 0;

        // 设置搜索条件 //
        $where = [];

        $userIds = [];
        if ($customer_name) {
            // array_push($where,['customer_id','=',$customer_id]);
            $userIds     = Db::name('customer')->where([['customer_name','like','%'.$customer_name.'%']])->column('id');
        }

        if ($shop_name) {
            $shopIds     = Db::name('shop')->where([['shop_name','like','%'.$shop_name.'%']])->column('shop_id');
            $userIds1     = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            $userIds     = empty($userIds) ? $userIds1 : array_merge($userIds,$userIds1);
        }
        if ($market_id) {
            $shopIds     = Db::name('shop')->where([['market_id','=',$market_id]])->column('shop_id');
            $userIds2    = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            $userIds     = empty($userIds) ? $userIds2 : array_merge($userIds,$userIds2);
        }
        if (!empty($userIds)) {
            array_push($where,['customer_id','in',$userIds]);
        }else if(empty($userIds) && ($customer_name || $shop_name || $market_id)){
            array_push($where,['customer_id','=',-1]);
        }
        // ['shop_name','market_name']
        // 读取列表 //
        // 获取的参数 //
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        if($shopIds){
            $userIds2 = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            array_push($where,['customer_id','in',$userIds2]);
        }
        // array_push($where,['shop_id','in',$shopIds]);
        $dataCount  = Db::name('coupon_provide_customer')->alias('cs')
            ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
            ->where($where)
            ->count();
        $field = 'cs.id,cs.customer_id,cs.coupon_id,cs.create_time,cs.use_time,cs.order_id,cs.order_sn,c.name,c.type,c.denomination,c.use_threshold,cs.user_id';
        $list  = Db::name('coupon_provide_customer')->alias('cs')
            ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
            ->field($field)
            ->where($where)
            ->limit(($page - 1) * $limit, $limit)->order('cs.id DESC')->select()->toArray();
        if($list)
        {
            $customer_ids    = array_values(array_unique(array_column($list, 'customer_id')));
            $customerList    = Db::name('customer')->where('id','in',$customer_ids)->column(['customer_name','shop_id'],'id');
            $shopIds         = array_values(array_unique(array_column($customerList, 'shop_id')));
            $shopList        = Db::name('shop')->where('shop_id','in',$shopIds)->column(['shop_name','shop_id','market_name'],'shop_id');
            $userIds         = array_values(array_unique(array_column($list, 'user_id')));
            $userList        = Db::name('admin_user')->where('id','in',$userIds)->column(['realname'],'id');
// print_r($shopList);
            //获取客户的相关数据
            foreach ($list as &$v) {
                $v['create_time']     = $v['create_time'] ? date('Y-m-d', $v['create_time']) : '';
                $v['use_time']        = $v['use_time'] ? date('Y-m-d', $v['use_time']) : '';
                $v['shop_name']       = $shopList[$customerList[$v['customer_id']]['shop_id']]['shop_name'] ?? '';
                $v['market_name']     = $shopList[$customerList[$v['customer_id']]['shop_id']]['market_name'] ?? '';
                $v['customer_name']   = $customerList[$v['customer_id']]['customer_name'];
                $v['user_name']       = $userList[$v['user_id']] ?? '';
                if ($v['type'] == 1) {
                    $v['type']        = '满减券';
                }else if ($v['type'] == 3) {
                    $v['type']        = '满赠券';
                }else{
                    $v['type']        = '兑换券';
                }
            }
        }
        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return resultArray(['data' => $data]);
    }

    /***
     * 获取优惠券的核销记录
     */
    public function getWriteOff_export()
    {
        $request = $this->param;
        // 获取需要的搜索参数 //
        // $page  = $request['page'] ?? 1;
        // $limit = $request['limit'] ?? 15;
        // $customer_name = $request['customer_name'] ?? 0;
        // $shop_name     = $request['shop_name'] ?? 0;
        // $market_id     = $request['market_id'] ?? 0;

        // // 设置搜索条件 //
        $where = [];

        // $userIds = [];
        // if ($customer_name) {
        //     // array_push($where,['customer_id','=',$customer_id]);
        //     $userIds     = Db::name('customer')->where([['customer_name','like','%'.$customer_name.'%']])->column('id');
        // }

        // if ($shop_name) {
        //     $shopIds     = Db::name('shop')->where([['shop_name','like','%'.$shop_name.'%']])->column('shop_id');
        //     $userIds1     = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
        //     $userIds     = empty($userIds) ? $userIds1 : array_merge($userIds,$userIds1);
        // }
        // if ($market_id) {
        //     $shopIds     = Db::name('shop')->where([['market_id','=',$market_id]])->column('shop_id');
        //     $userIds2    = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
        //     $userIds     = empty($userIds) ? $userIds2 : array_merge($userIds,$userIds2);
        // }
        // if (!empty($userIds)) {
        //     array_push($where,['customer_id','in',$userIds]);
        // }else if(empty($userIds) && ($customer_name || $shop_name || $market_id)){
        //     array_push($where,['customer_id','=',-1]);
        // }
        // // ['shop_name','market_name']
        // // 读取列表 //
        // // print_r($where);exit();
        // // 获取的参数 //

        $ids = $request['id'] ?? [];
        array_push($where,['id','in',$ids]);
        $dataCount  = Db::name('coupon_provide_customer')->alias('cs')
            ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
            ->where($where)
            ->count();
        $field = 'cs.id,cs.customer_id,cs.coupon_id,cs.create_time,cs.use_time,cs.order_id,cs.order_sn,c.name,c.type,c.denomination,c.use_threshold,cs.user_id';
        $list  = Db::name('coupon_provide_customer')->alias('cs')
            ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
            ->field($field)
            ->where($where)->order('cs.id DESC')->select()->toArray();
        if($list)
        {
            $customer_ids    = array_values(array_unique(array_column($list, 'customer_id')));
            $customerList    = Db::name('customer')->where('id','in',$customer_ids)->column(['customer_name','shop_id'],'id');
            $shopIds         = array_values(array_unique(array_column($customerList, 'shop_id')));
            $shopList        = Db::name('shop')->where('shop_id','in',$shopIds)->column(['shop_name','shop_id','market_name'],'shop_id');
            $userIds         = array_values(array_unique(array_column($list, 'user_id')));
            $userList        = Db::name('admin_user')->where('id','in',$userIds)->column(['realname'],'id');
// print_r($shopList);
            //获取客户的相关数据
            foreach ($list as &$v) {
                $v['create_time']     = $v['create_time'] ? date('Y-m-d', $v['create_time']) : '';
                $v['use_time']        = $v['use_time'] ? date('Y-m-d', $v['use_time']) : '';
                $v['shop_name']       = $shopList[$customerList[$v['customer_id']]['shop_id']]['shop_name'] ?? '';
                $v['market_name']     = $shopList[$customerList[$v['customer_id']]['shop_id']]['market_name'] ?? '';
                $v['customer_name']   = $customerList[$v['customer_id']]['customer_name'];
                $v['user_name']       = $userList[$v['user_id']] ?? '';
                if ($v['type'] == 1) {
                    $v['type']        = '满减券';
                }else if ($v['type'] == 2) {
                    $v['type']        = '满赠券';
                }else{
                    $v['type']        = '兑换券';
                }
            }
        }
        $callName = [
            'order_sn' => '订单编号',
            'customer_name' =>'客户名称',
            '' =>'核销人',
            'shop_name' => '店铺名称',
            'market_name' => '市场名称',
            'renameason' => '优惠券名称',
            'use_threshold' => '使用规则',
            'reason' => '面值',
            'create_time' => '领取时间',
            'use_time' => '使用时间',
        ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$list,'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    public function get_number_of_prompts(ReturnVistT $ReturnVistT): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['userInfo'] = $this->userInfo;
        $this->param['shopIds'] = $shopIds;
        $data = $ReturnVistT->getNumberOfPrompts($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取标签列表
     */
    public function read_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->read_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 新增标签
     */
    public function add_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->add_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 新增标签
     */
    public function read_member_label_info(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->read_member_label_info($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 编辑标签
     */
    public function save_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->save_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'编辑成功']);
    }

    /**
     * 获取二级标签接口
     */
    public function getTwoLabel(Setting $setting): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->getTwoLabel($this->param);
        // if (!$data) {
        //     return resultArray(['error' => $setting->getError()]);
        // }
        return resultArray(['data' => $data,'error'=>'获取成功']);
    }

    /**
     * 相册列表
     */
    public function albumList(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->albumList($this->param);
        // // if (!$data) {
        // //     return resultArray(['error' => $setting->getError()]);
        // // }
        return resultArray(['data' => $data,'error'=>'获取成功']);
    }

    /**
     * 新增相片
     */
    public function addAlbum(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->addAlbum($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error' => $CustomerModel->getError()]);
    }

    /**
     * 删除相片
     */
    public function deleteAlbum(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->deleteAlbum($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error'=>$CustomerModel->getError()]);
    }

    /**
     * 删除案例治疗记录照片
     */
    public function deleteCaseLogImg(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->deleteCaseLogImg($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error'=>$CustomerModel->getError()]);
    }

    /***
     *关闭服务
     */
    public function gbservice(Service $Service): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $Service->gbservice($this->param);
        // print_r($data);exit;
        return resultArray(['data'=>$data,'error'=>$Service->getError()]);
    }

    /***
     *删除服务记录
     */
    public function delservicelog(Service $Service): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $Service->delservicelog($this->param);
        // print_r($data);exit;
        return resultArray(['data'=>$data,'error'=>$Service->getError()]);
    }

    /***
     * 获取店铺列表
     */
    public function getTsShopList(): Json
    {
        $telephone = $this->param['telephone'] ?? 0;
        $shop_name = $this->param['shop_name'] ?? '';
        $cushopList = Db::name('customer')->where('telephone','=',$telephone)->column('shop_id');
        $where = [];
        array_push($where,['type','=',1]);
        array_push($where,['shop_type','=',2]);
        if($telephone){
            array_push($where,['shop_id','in',$cushopList]);
        }
        if($shop_name){
            array_push($where,['shop_name','like','%'.$shop_name.'%']);
        }
        $shopList = Db::name('shop')->where($where)->column('shop_id,shop_name');
        return resultArray(['data'=>$shopList,'error'=>'获取成功']);
    }

    /**
     * 处理直营店客户的余额数据
     */
    public function setZyCustomer()
    {

        // print_r(111111111111111111111);exit;
        $time = date('Ymd');
        $res = Db::name('customer_balance_tj')->where('time','=',$time)->find();
        if($res){
            return resultArray(['data'=>[],'error'=>'已被处理']);
        }
        $where = [];
        array_push($where,['type','=',1]);
        array_push($where,['shop_id','<>',73782774834649]);

        //$zyShopIds = Db::name('shop')->where('type','=',1)->column('shop_id');
        $zyShopIds = Db::name('shop')->where($where)->column('shop_id');
        /* echo '<pre>';
        print_r($zyShopIds); */
        //exit;

        // $zyCustomer = Db::name('customer')->where('shop_id','in',$zyShopIds)->column('customer_id');
        $zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_id');
        $b = ['time'=>$time];
        array_walk($zyB, function(&$val, $key) use ($b) {
            $val = array_merge($val, $b);
        });
        /* echo count($zyB);
        print_r($zyB);exit; */
        $res = Db::name('customer_balance_tj')->insertAll($zyB);

        return resultArray(['data'=>[],'error'=>'处理成功']);
    }


    /**
     * 创建订单
     * @return Json
     * @author SL
     * @create 2021-06-03
     */
    public function createYhjOrder(): Json
    {
        $this->param = request()->param();

        // 获取数据
        // $this->param['operator_id']   = $this->param['nurse_id'] ?? 0;
        // $this->param['operator_name'] = $this->param['nurse_id'];
        // 获取优惠券数据
        // $data = [
        //         [
        //             'id'=>2,
        //             'is_project'=>0,
        //             'type'=>0,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'',
        //         ],[
        //             'id'=>3,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'2021-06-03 12:12',
        //             'end_time'=>'2021-06-03 12:12',
        //             'num'=>'3',
        //         ],[
        //             'id'=>4,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'3',
        //         ]
        //     ];
        // print_r(json_encode($data));exit;
        $yhj_id     = $this->param['yhj_id'] ?? 0;
        $goods_list   = $this->param['goodsList'] ?? '';

        $incomeType     = $this->param['income_type'] ?? 0; //收入类型
        // print_r($goods_list_str);exit;
        // $goods_list = json_decode($goods_list_str,true);
        // print_r($goods_list);exit;
        $customerYhj = Db::name('coupon_provide_customer')->where('id','=',$yhj_id)->find();
        // print_r($customerYhj);//exit();
        if (empty($customerYhj)) {
            return resultArray(['error' => '优惠卷不存在']);
        }
        //获取优惠卷主表数据
        $yhjInfo = Db::name('coupon')->where('id','=',$customerYhj['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠卷不存在']);
        }
        //判断是否被使用
        if ($customerYhj['staus'] == 1) {
            return resultArray(['error' => '优惠券已被使用']);
        }
        if ($yhjInfo['type'] != 4) {
            return resultArray(['error' => '优惠券类型错误']);
        }
        // 判断是否过期
        $nowTime = time();
        if ($yhjInfo['start_time']>$nowTime) {
            // code...
            return resultArray(['error' => '优惠券未到兑换时间']);
        }
        if ($yhjInfo['end_time']<=$nowTime) {
            // code...
            return resultArray(['error' => '优惠券已过期']);
        }

        // 获取客户数据
        $customerTnfo = Db::name('customer')->where('id','=',$customerYhj['customer_id'])->find();
        // if ($customerTnfo['shop_id'] != $nurseInfo['shop_id']) {
        //     // code...
        //     return resultArray(['error' => '非本店客户，无法核销']);
        // }
        // 获取店铺数据
        $shopInfo = Db::name('shop')->where('shop_id','=',$customerTnfo['shop_id'])->find();
        $sshop_storeInfo = Db::name('shop_store')->where('id','=',$shopInfo['store_id'])->find();
        $shopInfo['store_kingdee_code'] = $sshop_storeInfo['kingdee_code'] ?? '';
        $nurse_id = $customerTnfo['nurse_id'];
        // 获取员工数据
        $nurseInfo = Db::name('shop_person')->where('id','=',$nurse_id)->find();
        if (empty($nurseInfo)) {
            // code...
            return resultArray(['error' => '员工信息不存在']);
        }
        // 获取订单商品数据
        $goodsIdArr = array_values(array_unique(array_column($goods_list,'id')));
        $sqlyhjGoodsList  = Db::name('shop_goods')->where('id','in',$goodsIdArr)->select()->toArray();
        // print_r($sqlyhjGoodsList);exit;
        $yhjGoodsList = [];
        foreach ($sqlyhjGoodsList as $key => $val){
            $yhjGoodsList[$val['id']] = $val;
        }
        // 验证
        $data = [
            'uid'               => $customerTnfo['id'], // 客户
            'consignee'         => $customerTnfo['customer_name'], // 收货人
            'order_no'          => $this->getOrderNo(), // 订单号
            'sale_id'           => $nurse_id, // 销售员id
            'sale_name'         => $nurseInfo['name'], // 销售员姓名
            'shop_id'           => $shopInfo['shop_id'], // 门店id
            'shop_name'         => trim($shopInfo['shop_name']), // 门店名称
            'operator_id'       => $nurseInfo['id'],//制单员id
            'operator_name'     => $nurseInfo['name'],//制单员姓名
            'create_time'       => time(), // 创建时间
            'deal_time'         => time(), // 成交日期
            'goods_price'       => 0, // 订单标准金额
            'total_amount'      => 0, // 订单总金额
            'pay_amount'        => 0, // 实收本金
            'discount_amount'   => 0, // 订单优惠金额
            'gift_amount'       => 0, // 实收赠金
            'order_amount'      => 0, // 订单优惠金额
            'is_experience'     => 0, // 是否体验 0否 1是
            'experience_id'     => 0, // 体验人id
            'experience_name'   => '', // 体验人姓名
            'is_outreach'       => 0, // 是否外联 0否 1是
            'coupon_id'         => $yhjInfo['id'], // 优惠券id
            'coupon_name'       => $yhjInfo['name'], // 优惠券id
            'outreahc_id'       => 0, // 外联人id
            'outreahc_name'     => '', // 外联人姓名
            'is_introduction'   => 0, // 是否转介绍 0否 1是
            'introduction_id'   => 0, // 转介绍人id
            'introduction_name' => '', // 转介绍人姓名
            'description'       => '', // 订单描述
            'order_type'        => 2, // 订单类型 1新单 2补单
            'business_type'     => 1, // 业务类型 1项目 2疤痕
            'income_type'       => $incomeType, // 收入类型 1服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
            'sales_policy'      => '', // 销售政策编码
            'market_id'         => $shopInfo['market_id'], // 市场id
            'market_name'       => $shopInfo['market_name'], // 市场名称
            'sales_organization'=> $shopInfo['market_kingdee_code'], // 销售组织编码
            'sales_name'        => $shopInfo['market_name'], // 销售组织名称
            'settlement_organization' => $shopInfo['market_kingdee_code'], // 结算组织编码
            'settlement_name'         => $shopInfo['market_name'], // 结算组织名称
            'delivery_name'       => $shopInfo['shop_name'], // 发货部门名称
            'delivery_king'       => $shopInfo['keycode'], // 发货部门编码
            'order_experience'        => 0 //订单是否有体验商品
        ];
        // print_r($data);exit;
        Db::startTrans();
        try {
            // if($yhj_id == 52){
            //     $orderId = 200;
            //     $member_products = 0;
            // }else{
            $orderId = Db::name('shop_order')->insertGetId($data);
            // }
            // $orderId = 200;
            // $member_products = 0;
            $orderGoodsList = [];
            $serviceDataAll = [];
            if ($orderId) {
                // print_r($yhjGoodsList);
                foreach ($goods_list as $k => $v) {
                    $thisGoods = $yhjGoodsList[$v['id']] ?? [];
                    if(empty($thisGoods)){
                        continue;
                    }
                    $oneArr = [];
                    $oneArr['order_id']     = $orderId;
                    $oneArr['create_time']  = time();
                    $oneArr['goods_id']     = $thisGoods['id'];
                    $oneArr['goods_name']   = $thisGoods['name'];
                    $oneArr['kingdee_code'] = $thisGoods['kingdee_code'];
                    $oneArr['goods_price']  = $thisGoods['goods_price'];
                    $oneArr['pay_price']    = 0;
                    $oneArr['spec_name']    = $thisGoods['spec_name'];
                    $oneArr['unit_code']    = $thisGoods['unit_code'];
                    $oneArr['unit_name']    = $thisGoods['unit_name'];
                    $oneArr['number']       = $v['number'];
                    $oneArr['desc']         = '';
                    $oneArr['is_project']   = $thisGoods['is_project'];//是否服务 1 是 2否
                    $oneArr['category_id']  = $thisGoods['category_id'];
                    $oneArr['is_coupon_goods'] = 1;//是否优惠券商品 0否 1是
                    $project_type = $v['project_type'] ?? 0;
                    $project_type = $project_type == 1 ?1:2;
                    $oneArr['project_type'] = $project_type;//服务类型 1 按次 2按天
                    $oneArr['service_number'] = isset($v['service_number']) ? $v['service_number'] : 0;//服务次数
                    $oneArr['start_time']     = isset($v['start_time']) ? strtotime($v['start_time']) : 0;
                    $oneArr['end_time'] = isset($v['end_time']) ? strtotime($v['end_time']) : 0;
                    $oneArr['is_gift']  = 1;
                    $oneArr['house_code'] = $shopInfo['store_kingdee_code'];
                    $oneArr['coupon_type'] = 4;//优惠券类型
                    $oneArr['house_code_name'] = $shopInfo['market_name'];
                    // print_r($v);
                    array_push($orderGoodsList,$oneArr);
                    if($v['is_project'] == 2 && $v['id'] != 170 && $v['id'] != 171){
                        for($i=1;$i<=$orderGoodsList[$k]['number'];$i++){
                            $oneService['name']    = $oneArr['goods_name'];  //服务名称
                            $oneService['num']     = $oneArr['service_number'];   // 必填--服务类型：1按期2按次
                            $oneService['shop_id'] = $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['service_type'] = $oneArr['project_type']==1?2:1;   // 必填--服务类型：1按期2按次
                            $oneService['start_time']   = $oneArr['start_time'];    // 类型为1是必填--服务开始时间
                            $oneService['end_time']     = $oneArr['end_time'];      // 类型为1是必填--服务开始时间
                            $oneService['experience']   = $data['is_experience'];     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id
                            $oneService['kk_money']     = $data['total_amount'];       // 开卡金额
                            $oneService['goods_id']     = $oneArr['goods_id'];       // 开卡金额
                            $oneService['category_id']  = $oneArr['category_id'];       // 开卡金额
                            array_push($serviceDataAll,$oneService);
                        }
                    }
                }
            }else{
                return resultArray(['error' => '核销失败']);
            }
            // if($yhj_id == 52){
            //     // print_r($orderGoodsList);exit;
            // }
            // print_r($orderGoodsList);exit;
            Db::name('shop_order_goods')->insertAll($orderGoodsList);

            //添加操作记录
            // $goods_name = array_column($orderGoodsList, 'goods_name');
            // $goods_name_str = implode('|', $goods_name);
            // $content = '创建订单：【'. $nurseInfo['name'] . '】创建了【' . $customerTnfo['customer_name'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
            // $code = [];
            // $code = $data;
            // $code['orderGoodsList']  = $orderGoodsList;
            // $this->addActionRecord($nurseInfo['id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
            // 处理客户的余额 //
            $customerModel = new \app\crm\model\Customer();
            $customer_id   = $data['uid'];    // 客户的id
            $balanceData   = [                // 余额变更数据集
                // 'change_type'  => 2,      // 变动类型 1:增加 2:减少
                // 'change_money' => $data['pay_amount'],      // 变更的本金
                // 'complimentary_money' => $data['gift_amount'],  // 变更的赠金
                // 'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
            ];
            $newOrderData  = [   // 新单变更数据集
                // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
                // 'cj_money'    => $total_amount,    // 成交金额
                // 'cj_order_id' => $orderId, // 成交的订单单号
            ];
            $orderInfo     = [       // 本次需要新增的订单金额
                // 'order_amount' => $total_amount, // 本次订单金额
                // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
            ];
            $member_products = 0; // 购买了几次会员商品
            $yhjOrderInfo  = [    // 本次需要处理的优惠卷
                'yhj_id'     => $yhj_id??0,      // 本次优惠卷的id
                'order_id'  => $orderId,   // 本次订单的id
                'order_no'  => $data['order_no'],   // 本次订单的id
                'operator_id' => $data['sale_id'],  // 核销人的id
            ];
            $customerModel->processingFunds($customer_id,$balanceData,$deal_time=0,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
            // print_r($serviceDataAll);exit;
            $customerModel->addCustomService($customer_id,$serviceDataAll);
            //处理成功，推送金蝶
            // exit;
            // 处理客户的余额 //
            // 客户推送金蝶
            if ($shopInfo['type'] != 2)
            {
                $res = $customerModel->pushKingCustomer($customer_id);
                if($res == false){
                    $error = $customerModel->getError();
                    return resultArray(['error' => $error]);
                }
                $kingDee = new Kingdee();
                $result=$kingDee->send_order($orderId);
                if ($result['code'])
                {
                    $error = $result['msg'];
                    return resultArray(['error' => $error]);
                }
            }
            Db::commit();
            $error = '创建成功';
            return resultArray(['data'=>[],'error' => $error]);
            // return true;
        }catch (\Exception $e) {
            Db::rollback();
            $error = $e->getMessage();
            // print_r($error);
            // return false;
        }
        return resultArray(['error' => $error]);
        // if (empty($orderGoodsList)) {
        //     // code...
        //     return resultArray(['error' => '无法获取商品数据，无法进行核销']);
        // }
        // Db::name('shop_order_goods')->insertAll($orderGoodsList);

        //     // 添加操作记录
        //     $goods_name = array_column($orderGoodsList, 'goods_name');
        //     $goods_name_str = implode('|', $goods_name);
        //     $content = '创建订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
        //     $code = [];
        //     $code = $data;
        //     $code['orderGoodsList']  = $orderGoodsList;
        //     $this->addActionRecord($request['operator_id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
        //     // 处理客户的余额 //
        //     $customerModel = new \app\crm\model\Customer();
        //     $customer_id   = $data['uid'];    // 客户的id
        //     $balanceData   = [                // 余额变更数据集
        //         'change_type'  => 2,      // 变动类型 1:增加 2:减少
        //         'change_money' => $data['pay_amount'],      // 变更的本金
        //         'complimentary_money' => $data['gift_amount'],  // 变更的赠金
        //         'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
        //         ];
        //     $newOrderData  = [   // 新单变更数据集
        //         // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
        //         // 'cj_money'    => $total_amount,    // 成交金额
        //         // 'cj_order_id' => $orderId, // 成交的订单单号
        //         ];
        //     $orderInfo     = [       // 本次需要新增的订单金额
        //         // 'order_amount' => $total_amount, // 本次订单金额
        //         // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
        //     ];
        //     // $member_products = 0; // 购买了几次会员商品
        //     $yhjOrderInfo  = [    // 本次需要处理的优惠卷
        //         'yhj_id '     => isset($request['yhj_id'])?$request['yhj_id']:0,      // 本次优惠卷的id
        //         'order_id  '  => $orderId,   // 本次订单的id
        //         'order_no  '  => $data['order_no'],   // 本次订单的id
        //         'operator_id' => $data['sale_id'],  // 核销人的id
        //     ];
        //     $customerModel->processingFunds($customer_id,$balanceData,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
        //     // print_r($serviceDataAll);exit;
        //     $customerModel->addCustomService($customer_id,$serviceDataAll);
        //     //处理成功，推送金蝶
        //     // exit;
        //     // 处理客户的余额 //
        //     // 客户推送金蝶
        //     if ($shop['type'] == 1)
        //     {
        //     $res = $customerModel->pushKingCustomer($customer_id);
        //     if($res == false){
        //         $this->error = $customerModel->getError();
        //         return false;
        //     }
        //         $kingDee = new Kingdee();
        //         $result=$kingDee->send_order($orderId);
        //         if ($result['code'])
        //         {
        //             $this->error = $result['msg'];
        //             return false;
        //         }
        //     }
        //     Db::commit();
        //     $this->error = '创建成功';
        //     return true;
    }

    /**
     * 生成订单号
     * @param  array $request 请求参数
     * @return String
     * @author SL
     * @create 2021-06-03
     */
    public function getOrderNo()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();
            if($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }


    /**
     * 员工预约列表
     * @param  SysModelMini $SysModelMini
     * @return Json
     */
    public function staffBooksList(SysModelMini $sysModelMini): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $sysModelMini->getStaffBookList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 获取黄v数据
     */
    public function getYellowV()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowV($this->param);

        return resultArray(['data' => $data]);


    }
    /**
     * 黄v客服详情页数据
     */
    public function getYellowVService()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowVService($this->param);

        return resultArray(['data' => $data]);



    }
    /**
     * 黄v护理师详情页
     */
    public function getYellowVPhysician()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowVPhysician($this->param);

        return resultArray(['data' => $data]);

    }

    /**
     * 预约列表
     *
     * @return Json
     */

    public function staffBooksList2()
    {
        $param = request()->param();
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $shopIds = [];
        array_push($shopIds,$param['shop_id']);
        $where = [];
        $startTime = strtotime($param['time']);
        if(empty($startTime))
        {
            $startTime = strtotime(date('Y-m-d'));
        }
        $endTime = $startTime+24*60*60-1;
        array_push($where,['b.yy_time','between',[$startTime,$endTime]]);
        array_push($where,['b.status','=',0]);
        array_push($where,['a.status','=',1]);
        if(!empty($shopIds))
        {
            array_push($where,['a.shop_id','in',$shopIds]);
        }
        $result = Db::name("shop_person")->alias('a')
            ->join("books b",'b.shop_person_id = a.id','left')
            ->join("customer c","b.customer_id = c.id",'left')
            ->field('b.yy_time,b.yy_time_str,b.shop_person_id,b.is_use,a.name as person_name,c.id,c.telephone,c.customer_name')
            ->where($where)
            ->select()->toArray();

//        var_dump($result);die;

        // echo "<pre>";
        // print_r($result);
        // echo "</pre>";
        // exit;
        $person = array_column($result,'shop_person_id');
        $where = [];
        array_push($where,['id','not in',$person]);
        array_push($where,['status','=',1]);


        if(!empty($shopIds))
        {
            array_push($where,['shop_id','in',$shopIds]);
        }
        $result2 = Db::name("shop_person")
            ->field('id as shop_person_id,name as person_name')
            ->where($where)
            ->select()->toArray();
        foreach ($result2 as $key => $value)
        {
            $result2[$key]['type']=1;
        }
        $result=array_merge($result,$result2);
        $data = [];
        $times = [];

        $shop_type = Db::name('shop')->where('shop_id',$param['shop_id'])->value('shop_type');

        if($shop_type == 1){

            $time_interval = 3600;

        }else{

            $time_interval = 1800;

        }
        for ($now = strtotime(date('Y-m-d')." 9:00");$now<=strtotime(date('Y-m-d')." 20:00");$now+=$time_interval)
        {
            array_push($times,date('H:i',$now));
        }



        foreach ($result as $key =>$value)
        {
            if(empty($data[$value['shop_person_id']]))
            {
                $data[$value['shop_person_id']]=[
                    'person_name'=>$value['person_name'],
                    'shop_person_id'=>$value['shop_person_id'],
                ];
//                $distribution = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                $distribution=[];
                for ($now = strtotime(date('Y-m-d')." 9:00");$now<=strtotime(date('Y-m-d')." 20:00");$now+=$time_interval)
                {
                    array_push($distribution,[
                        "status"=>2,
                        "customer"=>"",
                        "time"=>date('H:i',$now)
                    ]);
                }
                if(!empty($value['type']))
                {
                    $data[$value['shop_person_id']]['distribution']=$distribution;
                    continue;
                }

            }else{
                $distribution = $data[$value['shop_person_id']]['distribution'];
            }
            $time = explode(',',$value['yy_time_str']);
            if(empty($time))
            {
                $data[$value['shop_person_id']]['distribution']=$distribution;
                continue;
            }
            $start = (strtotime($param['time']." ".$time[0])-strtotime($param['time']." "."09:00"))/$time_interval;
            $end = (strtotime($param['time']." ".$time[count($time)-1])-strtotime($param['time']." "."09:00"))/$time_interval;
            for ($i = $start;$i<=$end;$i++)
            {
                $distribution[$i]['customer']=$value['customer_name'].$value['telephone'];
                $distribution[$i]['status']=$value['is_use'];
            }

            $data[$value['shop_person_id']]['distribution']=$distribution;
        }
        $data = array_merge($data,[]);
        return $this->success(['data'=>$data,'times'=>$times],"获取完成",count($data));
    }
    public function personcustomerList()
    {
        $param = request()->param();
        $personId = $param['person_id']??0;
        if(empty($personId))
        {
            return $this->failed(400,"参数错误");
        }
        $person  = PersonModel::find($personId);
        if(!$person)
        {
            return $this->failed(400,"参数错误");
        }
        $customer = new \app\crm\model\Customer();
        $where = [];
        array_push($where,['shop_id','=',$person->shop_id]);
//        array_push($where,['customer_name','like',"%".$param['name']."%"]);
        $customer = $customer->where($where)->field('id,customer_name,telephone')->select()->toArray();
        return $this->success($customer);
    }

    /**
     * 添加预约
     *
     * @return mixed
     */
    public function submitBooks()
    {
        $param = request()->param();
        $personId = $param['person_id']??0;
        $person  = PersonModel::find($personId);
        $params = [
            'shop_person_id'=>$personId,
            'customer_id'=>$param['customer_id'],
            'shop_id'=>$person->shop_id,
        ];
        if(empty($param['date']))
        {
            $params['yy_year']=date('Y');
            $params['yy_date']=date('m-d');
            $date = date('Y-m-d');
        }else{
            $dateStr = strtotime($param['date']);
            $params['yy_year']=date('Y',$dateStr);
            $params['yy_date']=date('m-d',$dateStr);
            $date = $param['date'];
        }
        $startTime = strtotime($date.$param['start_time']);
        $endTime = strtotime($date.$param['end_time']);
        $time = [];
        for ($now = $startTime;$now<=$endTime;$now+=30*60)
        {
            array_push($time,date('H:i',$now));
        }
        $params['yy_time']=$time;
        $model = new SysModelMiniCustomer();


        $data = $model->addYYData2($params,$this->app);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 获取预约记录id
     *
     * @return Json
     */
    public function getBookId()
    {
        $param = request()->param();
        if(empty($param['date']))
        {
            $date = date('Y-m-d');
        }else{
            $date = $param['date'];
        }
        $startTime = strtotime($date);
        $endTime = strtotime($date)+24*60*60;
        $where = [];
        array_push($where,['shop_person_id','=',$param['person_id']]);
        array_push($where,['yy_time','>=',$startTime]);
        array_push($where,['yy_time','<',$endTime]);
        array_push($where,['yy_time_str','like','%'.$param['start_time'].'%']);
        array_push($where,['cancel_time','=',0]);
        $book = Db::name('books')->where($where)->find();
        $bookId=$book['id'];
        return $this->success(['id'=>$bookId]);

    }








}
